#pragma once
#include <iostream>
#include <string>
#include <vector>
#include<sstream>

using namespace std;

const string HttpSep = "\r\n";
const string homepage="index.html";
const string wwwroot="./wwwroot";

class HttpRequest
{
public:
    HttpRequest() : _req_blank(HttpSep),_path(wwwroot)
    {
    }
    ~HttpRequest() {}

    bool GetLine(string &request, string *line)
    {
        auto pos = request.find(HttpSep);
        if (pos == string::npos)
        {
            return false;
        }
        *line = request.substr(0, pos);         // copy the line
        request.erase(0, pos + HttpSep.size()); // erase the line from the request
        return true;
    }
    bool Deserialize(string &request)
    {
        string line;
        bool ok = GetLine(request, &line);
        if (!ok)
            return false;
        _req_line = line; // 将第一行信息保存到_req_line中
        // 一直解析
        while (true)
        {
            bool ok = GetLine(request, &line);
            if (ok && line.empty())
            {
                _req_content = request; // http请求除了头部还有内容，所以把剩下的内容保存起来
                break;
            }
            else if (ok && !line.empty())
            {
                _req_header.push_back(line); // 将头部每一行信息保存到vector中
            }
            else
            {
                break;
            }
        }
        return true;
    }
    void Debug()
    {
        cout << "req_line" << _req_line << endl;
        for (auto &line : _req_header)
        {
            cout << "--->" << line << endl;
        }
        cout << "_req_blank :" << _req_blank << endl;
        cout << "_req_content   :" << _req_content << endl;

        cout<<"method:"<<_method<<endl;
        cout<<"url:"<<_url<<endl;
        cout<<"http_version:"<<_http_version<<endl;
    }
    void ParseReqLine()
    {
        stringstream ss(_req_line);
        ss>>_method>>_url>>_http_version;

        //处理url
        //如果访问的是根目录，就把首页给他
        if(_url=="/")
        {
            _path+=_url+homepage;
        }
        else
        {
            _path+=_url;
        }
    }
    void ParseSuffix()
    {
        //处理后缀
        auto pos = _path.rfind(".");
        if (pos == string::npos)
            _suffix = ".html";
        else
            _suffix = _path.substr(pos);
    }
    void Parse()
    {
        //1。分析请求，解析第一行
        ParseReqLine();
        //2.wwwroot
        ParseSuffix();
    }
    string GetUrl()
    {
        return _url;
    }
    string GetPath()
    {
        return _path;
    }
    string GetSuffix()
    {
        return _suffix;
    }
private:

    string _req_line;
    vector<string> _req_header;
    string _req_blank;
    string _req_content;

    //解析之后的内容
    string _method;
    string _url;
    string _http_version; 

    string _path;
    string _suffix;//请求资源后缀
};
